<template>
  <section class="todoapp">
    <todu-header @add="handAdd"></todu-header>
    <todu-main :list="list2" @del="shanchu" @state="headleState" @changeAllState="val => (list.forEach(item => item.isDone = val))"></todu-main>
    <todu-footer :list="list" :flag="flag" @changeFlag="val => flag=val" @clear="handlClear"></todu-footer>
  </section>
</template>

<script>
import ToduFooter from './components/TodoFooter.vue'
import ToduHeader from './components/TodoHeader.vue'
import ToduMain from './components/TodoMain.vue'
export default {
  components: { ToduHeader, ToduMain, ToduFooter },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todo-list'))||[],
      // list: [
      //   { id: 12, name: '吃饭', isDone: false },
      //   { id: 14, name: '听歌', isDone: true },
      //   { id: 23, name: '洗澡', isDone: true },
      //   { id: 34, name: '睡觉', isDone: false },
      //   { id: 35, name: '游戏', isDone: false },
      // ],
      flag: 1 //all表示全部任务，active表示进行中，completed表示已完成
    }
  },
  methods: {
    // screen(val) {
    //   this.flag = val
    // },
    shanchu (id) {
      this.list = this.list.filter(item => item.id != id)
    },
    handAdd(todo) {
      // this.list.push()  //push 向数组末尾添加一个元素
      // this.list.unshift()  //unshift 向数组前添加一个元素
      this.list.unshift({id:Date.now(),name:todo,isDone:false})
    },
    headleState(id) {
      let res = this.list.find(item => item.id === id)
      res.isDone = !res.isDone
    },
    handlClear () {
      // isDone== true 是已完成的
      this.list = this.list.filter(item => item.isDone === false)
    }
  },
  computed: {
    list2 () {
      if(this.flag === 2) {
        return this.list.filter(item => item.isDone === false)
      }else if(this.flag === 3) {
        return this.list.filter(item => item.isDone === true)
      }else {
        return this.list
      }
    }
  },
  watch: {
    list: {
      handler(val) {
        localStorage.setItem('todo-list',JSON.stringify(val))
      },
      // immediate:true, // 立即侦听 
      deep:true // 深度侦听（用于侦听对象属性的变化）
    }
  }
}
</script>

<style></style>
